package com.mch.func.file.html;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JFileChooser;

import org.mch.biz.ui.FuncEvent;
import org.mch.biz.ui.FuncPanel;
import org.mch.swingm.core.MFileChooser;

import com.mch.main.common.MEnv;

/**
 * 描述：编码操作工具事件；
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class HTMLFileEvent extends FuncEvent {
	private static final long serialVersionUID = 1L;

	public HTMLFileEvent(FuncPanel panel) {
		super(panel);
	}

	protected void onButtonClick(ActionEvent e) throws Exception {
		if (e.getSource() == getPanel().getBtn_file()) {
			browseFile();
		} else if (e.getSource() == getPanel().getBtn_html_lower()) {
			toHtmlLower();
		}
	}

	private MFileChooser browseFileChooser = new MFileChooser();

	public void browseFile() throws Exception {
		String[] selFileTypes = getPanel().getText_filetype().getText().split(",");
		browseFileChooser.setSelectFileType(selFileTypes);
		browseFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int yn = browseFileChooser.showOpenDialog(MEnv.MAINFRAME);
		File file = browseFileChooser.getSelectedFile();
		if (yn == 0 && file != null) {
			getPanel().getText_file().setText(file.getPath());
		}
	}

	public void toHtmlLower() throws Exception {
		File selfile = new File(getPanel().getText_file().getText());
		String encode = (String) getPanel().getCombo_encode().getSelectedItem();
		ToHTMLLowerHandler handle = new ToHTMLLowerHandler(selfile, encode, getFileTypeSet());
		String s = handle.handle();

		getPanel().getTextarea().setText(s);

	}

	private Set<String> getFileTypeSet() {
		String filetype = getPanel().getText_filetype().getText();
		String[] fts = filetype.split(",");
		Set<String> filetypeset = new HashSet<String>();
		for (int i = 0, len = fts.length; i < len; i++) {
			filetypeset.add(fts[i].toLowerCase());
		}
		return filetypeset;
	}

	public HTMLFilePanel getPanel() {
		return (HTMLFilePanel) super.getPanel();
	}
}